//
//  LXOAuthViewController.swift
//  weibo
//
//  Created by lixin on 16/4/16.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

import SVProgressHUD

class LXOAuthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setUI()
    }
    
    //MARK: - 设置视图
    private func setUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        
        setNav()
    }
    
    //MARK: - 设置导航栏
    private func setNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXOAuthViewController.cancel))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXOAuthViewController.autoWrite))
        
        navigationItem.title = "微博登录"
    }
    
    //MARK: - 点击方法
    @objc private func cancel(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoWrite(){
    
        let jsString = "document.getElementById('userId').value='\(weiboName)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //MARK: - 懒加载webView
    private lazy var webView: UIWebView = UIWebView()

}

//MARK: - webView代理方法
extension LXOAuthViewController:UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(REDIRECT_URI){
        
            if let query = request.URL?.query{
            
                let code = query.substringFromIndex("code=".endIndex)
                
                getUserAccount(code)
                
                return false
            }
        }
        
        
        return true
    }
}

extension LXOAuthViewController{

    func getUserAccount(code: String){
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            
            "client_id":APPKEY,
            
            "client_secret":APPSECRET,
            
            "grant_type":"authorization_code",
            
            "code":code,
            
            "redirect_uri":REDIRECT_URI
            
        ]
        
        LXNetworkTools.sharedTools.request(LXRequestMethod.POST, urlString: urlString, params: params) { (response, error) in
            
            if error != nil {
                
                print(error)
                
                return
            }
            
            guard let dataDict = response as? [String: AnyObject] else{
            
                print("返回的不是字典")
                
                return
            }
            
            let account = LXUserAccount(dict: dataDict)
            
            self.getUserInfo(account)
        }
    }
    
    func getUserInfo(acconut: LXUserAccount){
    
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
        
            "access_token": acconut.access_token!,
            
            "uid": acconut.uid!
        ]
        
        LXNetworkTools.sharedTools.request(LXRequestMethod.GET, urlString: urlString, params: params) { (response, error) in
            
            if error != nil{
            
                print(error)
                
                return
            }
            
            guard let dataDict = response as? [String: AnyObject] else{
            
                print("返回的不是字典")
                
                return
            }
            
            acconut.avatar_large = dataDict["avatar_large"] as? String
            
            acconut.screen_name = dataDict["screen_name"] as? String
            
            LXUserAccountTools.sharedTools.saveUserAccount(acconut)//保存数据
            
            self.dismissViewControllerAnimated(false, completion: { 
                
                NSNotificationCenter.defaultCenter().postNotificationName("chooseNav", object: nil)
            })
        }
    }
}
